﻿//=============================================================
// Copyright (C) 2015 福流网络
// 作 者：江怀玉
// 日 期：2015-4-22
// 描 述: 通用的单笔数据增删改
//        json:前端提交的数据
//        action:操作,insert,update,delete
//        entity:实体对象名称
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
// 1.00   2015/4/22     江怀玉           
//=============================================================
using System;
using System.Web;
using System.Text;
using System.Web.Script.Serialization;
using System.Collections.Generic;

using FL.Common;
using FL.DBModule;
using FL.DBModule.Sys;
using FL.Bussiness;
using FL.DAL;
using FL.Lite;
using FL.Bussiness.Sys;

namespace FL.Web.BackEnd
{
    public partial class DataSave : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
            string strAction = this.GetStringFromQueryString("action", "");
            string strEntity = this.GetStringFromQueryString("entity", "");
            string strTable = this.GetStringFromQueryString("table", "");
            string strFrom = this.GetStringFromQueryString("from", "");
            ///用于表单自定义
            string strFormID = this.GetStringFromQueryString("fromid", Guid.Empty.ToString());
            string flag = this.GetStringFromQueryString("flag", "");
            string strJson = "";
            //string strDeleteJson = "";
            if (flag == "1")
            {
                //string Forms = FLContext.Request.Form[0].ToString();
                //strJson = Forms;
                strJson = FLContext.Request.Form[0].ToString();
                
            }
            else
            {
                strJson = this.GetStringFromQueryString("json", "");
            }

            CreateBussniess(strEntity);
            BaseEntity instance = null;
            try
            {
                instance = (BaseEntity)Globals.JSONtoObject(strEntity, strJson);
            }
            catch { }
            if (instance == null)
            {
                strTable = strEntity;
            }
            if (strTable =="" || "insert,update,delete".IndexOf(strAction)<0 ) // 有实体的
            {
                string msg = "";
                switch (strAction)
                {
                    case "":
                        InsertOrUpdate(strEntity, strJson.Replace("[A]", "&"), strAction);
                        break;
                    case "insert":
                        try
                        {
                            InsertOrUpdate(strEntity, strJson.Replace("[A]", "&"), strAction);
                        }
                        catch (Exception ex)
                        {
                            msg = ex.Message;
                        }
                        HttpContext.Current.Response.Write(msg);
                        break;
                    case "delete":
                        delete(strEntity, strJson);
                        break;
                    case "setRight":
                        //SetRight(strJson);
                        break;
                    case "setQuery":
                        SetQuery(strJson);
                        break;
                    case "InitDataListTemplate":
                        if (instance == null)
                        {
                            strTable = strEntity;
                        }
                        else 
                        {
                            strTable = instance.GetTableName();
                        }
                        InitDataListTemplate(strTable,strEntity);
                        break;
                    case "setTableStruc":
                        try
                        {
                            //SetTableStruc(strJson);
                        }
                        catch (Exception ex)
                        {
                            msg = ex.Message;
                        }
                        HttpContext.Current.Response.Write(msg);
                        break;
                    case "deleteFile":
                        string path = this.GetStringFromQueryString("path", "");
                        string file = this.GetStringFromQueryString("file", "");
                        DeleteFile(path, file);
                        break;
                    case "singleupdate":
                        string field = GetStringFromQueryString("field", "");
                        string value = GetStringFromQueryString("value", "");
                        UpdateSingleFieldAction(strTable, field, strJson.Replace("[A]", "&"), value);
                        break;
                    case "batch":
                        BatchSave(strJson, strTable);
                        break;
                    case "mutibatchsave":
                        BatchMutiTableDataSave(strJson, strTable);
                        break;
                    default:
                        InsertOrUpdate(strEntity, strJson.Replace("[A]", "&"), strAction);
                        break;
                }
            }
            else // 没有实体的
            {
               switch (strAction)
                {
                    case "insert":
                        Insert(strTable, strJson.Replace("[A]", "&"));
                        break;
                    case "update":
                        Update(strTable, strJson.Replace("[A]", "&"));
                        break;
                    case "delete":
                        Delete(strTable, strJson);
                        break;
                    case "singleupdate":
                        string field = GetStringFromQueryString("field", "");
                        string value = GetStringFromQueryString("value", "");
                        UpdateSingleFieldAction(strTable, field, strJson.Replace("[A]", "&"), value);
                        break;
                    case "batchsave":
                        BatchSave(strJson, strTable);
                        Response.Write("1");
                        break;
                   case "mutibatchsave":
                        BatchMutiTableDataSave(strJson, strTable);
                        Response.Write("1");
                        break;
                }
            }
        }


       

        /// <summary>
        /// 创建业务逻辑实例
        /// </summary>
        /// <param name="entityName"></param>
        private  void CreateBussniess(string entityName)
        {
            this._bll = BaseBussnies.CreateInstance(entityName);
        }

        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        /// <param name="action"></param>
        private void InsertOrUpdate(string strEntity, string strJson,string action)
        {
            CreateBussniess(strEntity);
            BaseEntity instance = (BaseEntity)Globals.JSONtoObject(strEntity, strJson);
            _bll.entity = instance;
            System.Guid? keyValue = instance.GetKeyFieldValue();
            //数据验证
            string strMsg = instance.CheckData();
            if (strMsg != "")
            {
                HttpContext.Current.Response.Write(strMsg);
                return;
            }
            strMsg = instance.GetDataCheckMessage();
            if (strMsg != "")
            {
                HttpContext.Current.Response.Write(strMsg);
                return;
            }
            bool b;
            if (action == "")
            {
                if (instance.GetKeyFieldValue() == new System.Guid())
                {
                    action = "insert";
                }
            }
            string checkResult = _bll.CheckData();
            if (false == string.IsNullOrEmpty(checkResult))
            {
                HttpContext.Current.Response.Write(checkResult);
                return;
            }
            checkResult = _bll.CheckData(instance, this.Page);
            if (false == string.IsNullOrEmpty(checkResult))
            {
                HttpContext.Current.Response.Write(checkResult);
                return;
            }


            //// 如果是批量数据操作
            if (this.GetStringFromQueryString("isBatch", "false") == "true")
            {
                Insert(strEntity, strJson);
                return;
            }
            strMsg = "";
            //instance.Save();
            if (action == "insert")
            {
                if (null == (Globals.GetPropertyValue(instance, "add_user") as Guid?) || (Globals.GetPropertyValue(instance, "add_user") as Guid?) == Guid.Empty)
                {
                    Globals.SetPropertyValue(instance, "add_user", this.UserId);
                    Globals.SetPropertyValue(instance, "add_time", System.DateTime.Now);
                }
                b = _bll.Insert(out strMsg);
            }
            else
            {
                if (null == (Globals.GetPropertyValue(instance, "modify_user") as Guid?) || (Globals.GetPropertyValue(instance, "modify_user") as Guid?) == Guid.Empty)
                {
                    Globals.SetPropertyValue(instance, "modify_user", this.UserId);
                    Globals.SetPropertyValue(instance, "modify_time", System.DateTime.Now);
                }
                checkResult = _bll.EditCheckData();
                if (false == string.IsNullOrEmpty(checkResult))
                {
                    HttpContext.Current.Response.Write(checkResult);
                    return;
                }
                b = _bll.Update(out strMsg);
            }
            if (b)
            {
                try
                {
                    ///写入日志
                    BWriteDataLog.Instance.SaveLog(this.UserId, instance, action,this.FunctionID);
                }catch{};
                HttpContext.Current.Response.Write("1");
            }
            else
            {
                HttpContext.Current.Response.Write(strMsg);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        private void delete(string strEntity, string strJson)
        {
            string checkResult = _bll.DeleteCheckData();
            if (false == string.IsNullOrEmpty(checkResult))
            {
                HttpContext.Current.Response.Write(checkResult);
                return;
            }
            DataTableBaseEntity instance =  new DataTableBaseEntity(); ;

            instance.TableName = strEntity;

            BaseBussnies bll = _bll;
            bll.entity = instance;

            string key = instance.getKey();

            if (string.IsNullOrEmpty(strJson))
            {
                strJson = this.GetStringFromQueryString("id", "");
                System.Data.DataTable dt =  _bll.GetDataBySqlComm("select * from "+strEntity +" where "+key+"='"+strJson+"'");
                instance.CreateDT(dt);
                bool bl = bll.delete(key + "='" + strJson + "'");
                try
                {
                    if (bl)
                        BWriteDataLog.Instance.SaveLog(this.UserId, instance, "delete",this.FunctionID);//.SaveLog(this.UserId, instance, "delete");
                }
                catch { }
               
                HttpContext.Current.Response.Write("1");
            }
            else
            {
                string[] strarr = strJson.Split(',');
                foreach (var s in strarr)
                {
                    strJson = this.GetStringFromQueryString("id", "");
                    System.Data.DataTable dt = _bll.GetDataBySqlComm("select * from " + strEntity + " where " + key + "='" + strJson + "'");
                    instance.CreateDT(dt);
                    bool bl  = bll.delete(key + "='" + s + "'");
                    try
                    {
                        if (bl)
                            BWriteDataLog.Instance.SaveLog(this.UserId, instance, "delete",this.FunctionID);//.SaveLog(this.UserId, instance, "delete");
                    }
                    catch { }
                }


                HttpContext.Current.Response.Write("1");
            }
        }


        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="TableName">表名/实体名</param>
        void InitDataListTemplate(string TableName,string EntityName)
        {
            string sql = string.Format("Exec sp_InitDataListTemplate '{0}','{1}'", TableName, EntityName);
            DbSql dbsql = new DbSql();
  
            if (dbsql.ExecuteSql(sql) > 0)
            {
                FLContext.Response.Write("1");
            }
            else
            {
                FLContext.Response.Write("0");
            }
        }



        /// <summary>
        /// 获取单行数据的操作Sql Command
        /// </summary>
        /// <param name="table">对应表</param>
        /// <param name="json">json数据</param>
        /// <returns></returns>
        private string GetSingleRowDataCommand(string table, string json,out string msg)
        {
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            string[] strKeyArrary = instance.GetKey();
            if (strKeyArrary != null)
            {
                instance.KeyField = strKeyArrary[0];
                instance.KeyFieldDataType = strKeyArrary[1];
            }
            instance.CreateDT();
            instance.EntityJson = json;
            instance.FieldValue = Globals.ConvertToDictionary(instance.EntityJson);
            if (instance.FieldValue.ContainsKey("add_user"))
            {
                instance.FieldValue["add_user"] = this.UserId;
            }
            if (instance.FieldValue.ContainsKey("add_time"))
            {
                if (instance.FieldValue["add_time"] == null)
                {
                    instance.FieldValue["add_time"] = System.DateTime.Now;
                }
            }

            if (instance.FieldValue.ContainsKey("rec_id"))
            {
                instance.FieldValue.Remove("rec_id");
            }
            instance.SetValue(instance.FieldValue);

            ///---------------------------------
            ///验证不通过
            ///---------------------------------
            msg = instance.CheckData();
            StringBuilder sqlCommand = new StringBuilder("").AppendLine();
            BaseBussnies bll = new BaseBussnies(instance);
            msg = msg + bll.CheckData();
            sqlCommand.Append(bll.GetSqlCommand(instance));
            return sqlCommand.ToString();
        }


        /// <summary>
        /// 删除数据命令
        /// </summary>
        /// <returns></returns>
        private string getMulitRowsDeleteCommand()
        {
            string strDeleteJson = FLContext.Request.Form.Count > 1 ? FLContext.Request.Form[1].ToString() : "";
            return getMulitRowsDeleteCommand(strDeleteJson);
        }
        
        /// <summary>
        /// 获取删除数据操作Sql Command
        /// </summary>
        /// <param name="deleteJson">要删除的对应的数据信息</param>
        /// <returns></returns>
        private string getMulitRowsDeleteCommand(string deleteJson)
        {
            IList<json_data> list = FL.Common.Globals.JSonToObject<IList<json_data>>(deleteJson);
            StringBuilder deleteCommand = new StringBuilder("");
            if (list != null)
            {
                
                foreach (json_data data in list)
                {
                    if(!string.IsNullOrEmpty(data.key_value)){
                        deleteCommand.AppendLine(string.Format("delete from {0} where {1}='{2}'", data.table, data.key_field, data.key_value));
                    }
                }
            }
            return deleteCommand.ToString();
        }

       
        /// <summary>
        /// 获取多行数据的操作Sql Command
        /// </summary>
        /// <param name="table">对应表</param>
        /// <param name="json">json数据</param>
        /// <returns></returns>
        private string GetMulitRowsDataCommand(string table,string json,out string msg)
        {
            StringBuilder sqlCommand = new StringBuilder("");
            JavaScriptSerializer s = new JavaScriptSerializer();
            object[] list = (object[])s.DeserializeObject(json);
            BaseBussnies bll = new BaseBussnies();
            msg = "";
            foreach (object o in list)
            {
                DataTableBaseEntity DetailInstance = new DataTableBaseEntity();
                DetailInstance.TableName = table;
                string[] strKeyArrary = DetailInstance.GetKey();
                if (strKeyArrary != null)
                {
                    DetailInstance.KeyField = strKeyArrary[0];
                    DetailInstance.KeyFieldDataType = strKeyArrary[1];
                }
                DetailInstance.CreateDT();
                Dictionary<string, object> d = o as Dictionary<string, object>;
                DetailInstance.FieldValue = d;
                DetailInstance.SetValue(d);

                if (DetailInstance.KeyFieldDataType == "uniqueidentifier")
                {
                    if (DetailInstance[DetailInstance.KeyField].ToString() == "")
                    {
                        DetailInstance[DetailInstance.KeyField] = Guid.NewGuid();
                    }
                }

                if (DetailInstance.FieldValue.ContainsKey("RecID"))
                {
                    DetailInstance.FieldValue.Remove("RecID");
                }
                bll.entity = DetailInstance;
                msg = bll.CheckData(DetailInstance, this);
                sqlCommand.Append(bll.GetSqlCommand(DetailInstance));
            }
            return sqlCommand.ToString();
        }
       

        /// <summary>
        /// 批量保存(单表数据)
        /// </summary>
        /// <param name="strJson"></param>
        void BatchSave(string strJson, string detailTable)
        {
            string msg = "";
            string sqlCommand = getMulitRowsDeleteCommand();
            sqlCommand = sqlCommand + GetMulitRowsDataCommand(detailTable, strJson, out msg);
            if (msg == "")
            {
                msg = "";
                BaseBussnies bll = new BaseBussnies();
                int i = bll.RunSqlCommand(sqlCommand.ToString(), out msg);
                if (msg == "")
                {
                    Response.Write("1");
                }
                else
                {
                    Response.Write(msg);
                }
            }
            else
            {
                Response.Write(msg);
            }
        }


        /// <summary>
        /// 批量提交数据时候
        /// </summary>
        /// <param name="strJSON">数据以[@@@]分隔</param>
        /// <param name="tables">表，以":"分隔</param>
        void BatchMutiTableDataSave(string strJSON,string tables,string sqlstr="")
        {
            string[] s1 = { "[@@@]" };
            string[] dataArray = strJSON.Split(s1, StringSplitOptions.None);
            string[] tableArray = tables.Split(':');

            //数据删除
            StringBuilder sqlCommand = new StringBuilder("");
            StringBuilder message = new StringBuilder("");
            
            for (int i = 0; i < tableArray.Length; i++)
            {
                string msg = "";
                string _table = tableArray[i];
                string _json = dataArray[i];
                string _sql = "";
                if (_json.StartsWith("["))//多行数据
                {
                    _sql = GetMulitRowsDataCommand(_table, _json, out msg);
                }
                else
                {
                    _sql = GetSingleRowDataCommand(_table, _json, out msg);
                }
                if (msg != "")
                {
                    message.AppendLine(msg);
                }

                sqlCommand.AppendLine(_sql);
            }
            if (message.ToString() == "")
            {
                sqlCommand.AppendLine(getMulitRowsDeleteCommand());
                this._bll.RunSqlCommand(sqlCommand.ToString());
                Response.Write("1");
            }
            else
            {
                Response.Write(message.ToString());
            }
        }

      

        /// <summary>
        /// 创建表
        /// </summary>
        /// <param name="TableName"></param>
        public void SetTable(string TableName)
        {
            //BLL.Extend.DBTable dbTable = SqlDBTable.Instance;
            //dbTable.CreateTable(TableName);
        }

        /// <summary>
        /// 设置查询
        /// </summary>
        /// <param name="strJson"></param>
        private void SetQuery(string strJson)
        {
            QuerySolution entity = (QuerySolution)Globals.JSonToObject<QuerySolution>(strJson);
            //entity.BaseEntityState = WorkState.New;
            entity.EntityName = this.EntityName;
            entity.FunctionID = this.FunctionID;
            entity.add_user = this.UserId;
            entity.add_time = DateTime.Now;
            string action="";

            if(entity.QueryId==null||entity.QueryId == Guid.Empty)
            {
                action = "insert";
                entity.QueryId = Guid.Empty;
            }

            //BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
            _bll.entity = entity;
            if (entity.IsDefault == "Y")
            {
                _bll.RunSqlCommand("update Set_QuerySolution set IsDefault='N' where add_user='" + this.UserId + "' and FunctionID='" + entity.FunctionID + "'");
            }
            bool b;
            if (action == "insert")
            {
                b = _bll.Insert();
            }
            else
            {
                b = _bll.Update();
            }
            if (b)
            {
                Response.Write("1");
            }
            else
            {
                Response.Write("0");
            }
        }


        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="File"></param>
        private void DeleteFile(string FilePath,string File)
        {
            string path = this.MapPath(FilePath);
            System.IO.File.Delete(path + File);
        }

        #region No Entity
        /// <summary>
        /// 实现没有实体的操作
        /// </summary>
        /// <param name="table"></param>
        /// <param name="json"></param>
        public void Insert(string table, string json)
        {
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            string detailTable = GetDetailTable(GetStringFromQueryString("formid", Guid.Empty.ToString()), table);
            string[] strKeyArrary = instance.GetKey();
            if (strKeyArrary != null)
            {
                instance.KeyField = strKeyArrary[0];
                instance.KeyFieldDataType = strKeyArrary[1];
            }
            instance.CreateDT();
            string[] s1 = { "[@@@]" };
            string[] strArray = json.Split(s1, StringSplitOptions.None);
            //json_data data = FL.Common.Globals.JSonToObject<json_data>(strArray[0]);
            instance.EntityJson = strArray[0];//json;// FL.Common.Globals.DataRowToJSON(instance.DRow);
            instance.FieldValue = Globals.ConvertToDictionary(instance.EntityJson);
            if (instance.FieldValue.ContainsKey("add_user"))
            {
                instance.FieldValue["add_user"] = this.UserId;
            }
            if (instance.FieldValue.ContainsKey("add_time"))
            {
                instance.FieldValue["add_time"] = System.DateTime.Now;
            }

            if (instance.FieldValue.ContainsKey("RecID"))
            {
                instance.FieldValue.Remove("RecID");
            }
            instance.SetValue(instance.FieldValue);

            ///---------------------------------
            ///验证不通过
            ///---------------------------------
            string msg = instance.CheckData();
            if (!String.IsNullOrEmpty(msg))
            {
                Response.Write(msg);
                return;
            }

            //instance.SetPropertyValue("", "");
            StringBuilder sqlCommand = new StringBuilder("").AppendLine();
            BaseBussnies bll = new BaseBussnies(instance);
            msg = bll.CheckData(instance, this);
            if (!String.IsNullOrEmpty(msg))
            {
                Response.Write(msg);
                return;
            }
            sqlCommand.Append(bll.GetSqlCommand(instance));
            string strMsg = "";
            if (!string.IsNullOrEmpty(detailTable))
            {
                if (strArray.Length > 1)
                {
                    JavaScriptSerializer s = new JavaScriptSerializer();
                    object[] list = (object[])s.DeserializeObject(strArray[1]);
                    foreach (object o in list)
                    {
                        DataTableBaseEntity DetailInstance = new DataTableBaseEntity();
                        DetailInstance.TableName = detailTable;
                        strKeyArrary = DetailInstance.GetKey();
                        if (strKeyArrary != null)
                        {
                            DetailInstance.KeyField = strKeyArrary[0];
                            DetailInstance.KeyFieldDataType = strKeyArrary[1];
                        }
                        DetailInstance.CreateDT();
                        Dictionary<string, object> d = o as Dictionary<string, object>;
                        DetailInstance.FieldValue = d;
                        DetailInstance.SetValue(d);

                        if (DetailInstance.KeyFieldDataType == "uniqueidentifier")
                        {
                            if (DetailInstance[DetailInstance.KeyField].ToString() == "")
                            {
                                DetailInstance[DetailInstance.KeyField] = Guid.NewGuid();
                            }
                        }

                        if (DetailInstance.FieldValue.ContainsKey("rec_id"))
                        {
                            DetailInstance.FieldValue.Remove("rec_id");
                        }
                        if (((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)DetailInstance).KeyField] == null || ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)instance).KeyField].ToString() != string.Empty)
                        {
                            ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)DetailInstance).KeyField] = Guid.NewGuid();
                        }
                        //entity.SetFieldValue(entity, e.FieldName, MasterEntity.GetKeyFieldValue());
                        //DetailInstance.SetFieldValue(DetailInstance, DetailInstance.GetFKey()[0].FieldName, instance.GetKeyFieldValue());
                        bll.entity = DetailInstance;
                        msg = bll.CheckData(DetailInstance, this);
                        if (!String.IsNullOrEmpty(msg))
                        {
                            Response.Write(msg);
                            return;
                        }
                        sqlCommand.Append(bll.GetSqlCommand(DetailInstance));
                    }
                    int i = bll.RunSqlCommand(sqlCommand.ToString(), out strMsg);
                    if (i > -1)
                    {
                        FLContext.Response.Write("1");
                        return;
                    }
                    else
                    {
                        FLContext.Response.Write(strMsg);
                        return;
                    }
                }
            }

            if (table.Substring(0, 4) != "bpm_")//非BPM的表格
            {
                try
                {
                    this.InsertOrUpdate(table, json, GetStringFromQueryString("action", "insert"));
                    return;
                }
                catch { };
            }
            // 
            strMsg = "";
            if (bll.Insert(out strMsg))
            {
                FLContext.Response.Write("1");
            }
            else
            {
                FLContext.Response.Write(strMsg);
            }
        }

        /// <summary>
        /// 批量保存数据
        /// </summary>
        /// <param name="jsonData"></param>
        public void BatchSaveData(string jsonData)
        {

        }


        public void Update(string table, string json)
        {
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            string detailTable = GetDetailTable(GetStringFromQueryString("formid", Guid.Empty.ToString()), table);
            string[] strArrary = instance.GetKey();
            if (strArrary != null)
            {
                instance.KeyField = strArrary[0];
                instance.KeyFieldDataType = strArrary[1];
            }
            instance.CreateDT();
            string[] s1 = { "[@@@]" };
            string[] strArray = json.Split(s1, StringSplitOptions.None);
            instance.EntityJson = strArray[0];// FL.Common.Globals.DataRowToJSON(instance.DRow);
            instance.FieldValue = Globals.ConvertToDictionary(instance.EntityJson);
            if (instance.FieldValue.ContainsKey("edit_user"))
            {
                instance.FieldValue["edit_user"] = this.UserId;
            }
            if (instance.FieldValue.ContainsKey("edit_date"))
            {
                instance.FieldValue["edit_date"] = System.DateTime.Now;
            }
            //含有自增字段
            if (instance.FieldValue.ContainsKey("rec_id"))
            {
                instance.FieldValue.Remove("rec_id");
            }
            instance.SetValue(instance.FieldValue);
            StringBuilder sqlCommand = new StringBuilder("").AppendLine();
            BaseBussnies bll = new BaseBussnies(instance);
            string msg = bll.CheckData(instance, this);
            if (!String.IsNullOrEmpty(msg))
            {
                Response.Write(msg);
                return;
            }
            sqlCommand.Append(bll.GetSqlCommand(instance));
            // 将旧的数据清空
            if (!string.IsNullOrEmpty(detailTable))
            {
                if (strArray.Length > 1)
                {
                    JavaScriptSerializer s = new JavaScriptSerializer();
                    object[] list = (object[])s.DeserializeObject(strArray[1]);
                    int _count = 0;
                    foreach (object o in list)
                    {
                        DataTableBaseEntity DetailInstance = new DataTableBaseEntity();
                        DetailInstance.TableName = detailTable;
                        strArray = DetailInstance.GetKey();
                        if (strArray != null)
                        {
                            DetailInstance.KeyField = strArray[0];
                            DetailInstance.KeyFieldDataType = strArray[1];
                        }
                        DetailInstance.CreateDT();

                        Dictionary<string, object> d = o as Dictionary<string, object>;
                        DetailInstance.FieldValue = d;
                        DetailInstance.SetValue(d);
                        bll.entity = DetailInstance;
                        // 加入
                        if (_count == 0)
                        {
                            IList<SysTableFKey> fkList = DetailInstance.GetFKey();
                            if (fkList != null)
                            {
                                foreach (var e in fkList)
                                {
                                    if (e.FKTableName == instance.GetTableName())
                                    {
                                        sqlCommand.Append(string.Format("Delete from {0} where {1}", DetailInstance.GetTableName(), e.FieldName + "='" + instance.GetTableIdValue() + "'"));
                                    }

                                }
                            }
                        }
                        _count = 1;
                        sqlCommand.Append(bll.GetSqlCommand(DetailInstance));
                    }
                }
                else
                {
                    DataTableBaseEntity DetailInstance = new DataTableBaseEntity();
                    DetailInstance.TableName = detailTable;
                    strArray = DetailInstance.GetKey();
                    if (strArray != null)
                    {
                        DetailInstance.KeyField = strArray[0];
                        DetailInstance.KeyFieldDataType = strArray[1];
                    }
                    DetailInstance.CreateDT();
                    IList<SysTableFKey> fkList = DetailInstance.GetFKey();
                    if (fkList != null)
                    {
                        foreach (var e in fkList)
                        {
                            if (e.FKTableName == instance.GetTableName())
                            {
                                sqlCommand.Append(string.Format("Delete from {0} where {1}", DetailInstance.GetTableName(), e.FieldName + "='" + instance.GetTableIdValue() + "'"));
                            }
                        }
                    }
                }
                int i = bll.RunSqlCommand(sqlCommand.ToString());
                Response.Write("1");
                return;
            }
            if (bll.Update())
            {
                FLContext.Response.Write("1");
            }
        }

        /// <summary>
        /// 创建DataTableEntity实例
        /// </summary>
        /// <param name="table">表</param>
        /// <returns>DataTableBaseEntity对象</returns>
        private DataTableBaseEntity  CreateDatatableEntityInstance(string table)
        {
            string[] strArray = ",".Split(',');
            DataTableBaseEntity DetailInstance = new DataTableBaseEntity();
            DetailInstance.TableName = table;
            strArray = DetailInstance.GetKey();
            if (strArray != null)
            {
                DetailInstance.KeyField = strArray[0];
                DetailInstance.KeyFieldDataType = strArray[1];
            }
            DetailInstance.CreateDT();
            return DetailInstance;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="table"></param>
        /// <param name="json"></param>
        public void Delete(string table, string json)
        {
            string strEntity = table;
            string strJson = json;
            if (string.IsNullOrEmpty(json))
            {
                json = GetStringFromQueryString("id", "");
            }
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            string[] strArrary = instance.GetKey();
            if (strArrary != null)
            {
                instance.KeyField = strArrary[0];
                instance.KeyFieldDataType = strArrary[1];
            }
            string[] ids = json.Split(',');
            try
            {

                foreach (string id in ids)
                {
                    if (string.IsNullOrEmpty(strJson))
                    {
                        strJson = this.GetStringFromQueryString("id", "");
                        System.Data.DataTable dt = _bll.GetDataBySqlComm("select * from " + strEntity + " where " + instance.KeyField + "='" + id + "'");
                        bool bl = instance.Delete(id);
                        instance.CreateDT(dt);
                        //bool bl = bll.delete(key + "='" + strJson + "'");
                        try
                        {
                            if (bl)
                                BWriteDataLog.Instance.SaveLog(this.UserId, instance, "delete",this.FunctionID);//.SaveLog(this.UserId, instance, "delete");
                        }
                        catch { }
                    }
                }
                FLContext.Response.Write("1");
            }
            catch (Exception e){
                FLContext.Response.Write(e.Message);
            }
        }

        /// <summary>
        /// 更新某个字段值
        /// </summary>
        /// <param name="table">表名</param>
        /// <param name="field">更新字段</param>
        /// <param name="json">ID的串</param>
        /// <param name="value">更新的值</param>
        public void UpdateSingleFieldAction(string table, string field, string json, string value)
        {
            string ids = json;
            if (string.IsNullOrEmpty(ids))
            {
                ids = GetStringFromQueryString("id", "");
            }
            DataTableBaseEntity instance = new DataTableBaseEntity();
            instance.TableName = table;
            
            string[] strArrary = instance.GetKey();
            if (strArrary != null)
            {
                instance.KeyField = strArrary[0];
                instance.KeyFieldDataType = strArrary[1];
            }
            string[] _ids = json.Split(',');
            string updateSql = "update {0} set {1}='{2}' where {3}='{4}'";
            StringBuilder SqlComm = new StringBuilder("");
            try
            {
                foreach(string id in _ids)
                {
                    SqlComm.AppendLine(string.Format(updateSql, table, field, value,instance.KeyField,id));
                }
                _bll.entity = instance;
                _bll.RunSqlCommand(SqlComm.ToString());
                FLContext.Response.Write("1");
            }
            catch (Exception e)
            {
                FLContext.Response.Write(e.Message);
            }
        }
        #endregion

        /// <summary>
        /// 初始数据
        /// </summary>
        /// <param name="strFormID"></param>
        /// <param name="strEntity"></param>
        private string GetDetailTable(string strFormID, string strEntity)
        {
            if (strFormID == "")
            {
                strFormID = Guid.Empty.ToString();
            }
            t_sys_custom_define_form FormEntity = _bll.GetEntityByCondition<t_sys_custom_define_form>("id='" + strFormID + "' or master_tablename='" + strEntity + "'");
            if (FormEntity != null)
            {
                return GetDetailTable(FormEntity.detail_json);
            }
            return "";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="DetailsJson"></param>
        /// <returns></returns>
        private string GetDetailTable(string DetailsJson)
        {
            if (!string.IsNullOrEmpty(DetailsJson))
            {
                IList<SysDetailsItem> list = FL.Common.Globals.JSonToObject<IList<SysDetailsItem>>(DetailsJson);
                StringBuilder _details = new StringBuilder("");
                foreach (var _detail in list)
                {
                    return _detail.DetailsTableName;
                }
                //DetailsInstance = _details.ToString();
            }
            return "";
        }
    }


    internal class json_data
    {
        public string table
        {
            get;
            set;
        }

        public string key_field
        {
            get;
            set;
        }

        public string key_value
        {
            get;
            set;
        }
    }
}